package view {
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Shape;
	import flash.events.Event;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	
	import model.vo.PhotoVO;
	
	import mx.containers.Canvas;
	import mx.controls.Alert;
	import mx.controls.Button;
	import mx.controls.Image;
	import mx.core.FlexGlobals;
	import mx.core.UIComponent;
	
	import org.osflash.signals.Signal;
	
	import spark.components.Group;
	import spark.primitives.Rect;
	
	public class Photo extends Canvas {
		
		private var image:Image;
		public var completed:Signal = new Signal();
		
		private var vo:PhotoVO;
		private var appWidth:Number;
		private var appHeight:Number;
		private var container:UIComponent;
		
		private var _count:int;
		public function Photo(photo:PhotoVO, appWidth:Number, appHeight:Number) {
			vo = photo;
			this.appWidth = appWidth;
			this.appHeight = appHeight;
			
			
			image = new Image();
			image.smoothBitmapContent = true;
			image.source = photo.url;
			addChild(image);
			image.addEventListener(Event.COMPLETE, loadComplete);
			var shape:UIComponent = new UIComponent();
			shape.graphics.lineStyle(4,0xFF0000)
			shape.graphics.drawCircle(photo.width/ 100 * photo.x, photo.height / 100 * photo.y, 4);
			addChild(shape);
			
			
		}
		private function loadComplete(event:Event):void
		{
			vo.photo = this;
			vo = FaceDectector.instance.detect(vo);
			position();
			completed.dispatch();
		}
		
		public function position():void
		{
			var tagPos:Point = new Point(vo.width/ 100 * vo.x, vo.height / 100 * vo.y);	
			//var offset:Point = new Point(vo.width / 2 - tagPos.x, vo.height / 2 - tagPos.y);
			if (vo.faces.length>0) {
				
				var face:Rectangle = vo.faces[0];
				
				
				
				var scaleFactorX:Number = 100/ face.width;
				var scaleFactorY:Number = 100/face.height;
				
				
				scaleY = scaleFactorY;
				scaleX = scaleFactorX;
				
				
				
			
			
				callLater(later, [scaleFactorX]);
				
				var shape:UIComponent = new UIComponent();
				shape.graphics.lineStyle(4,0xFFFFFF,0.5)
				shape.graphics.drawCircle(face.width*.5, face.height,4);
				
				shape.graphics.drawRect(face.x,face.y,face.width,face.height);
				//var newPos:Point = this.localToGlobal(new Point(face.x,face.y));
				//trace(newPos+"   "+face.x+"   "+face.y)
				//face.x = newPos.x;
				//face.y = newPos.y;
				addChild(shape);		
			} else {				
				// remove and destroy usless image
				Group(this.parent).removeElement(this);
			}
			
			
		}
		
		private function later(sfX:Number):void {
			x = 225 - vo.width * sfX / 4;
		}
		
		
		public function get bitmapData():BitmapData
		{
			
			return Bitmap(image.content).bitmapData
		}
		
	}
}